package io.renren.modules.sys.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import io.renren.common.exception.BizException;
import io.renren.common.vo.RV;
import io.renren.modules.sys.entity.User;
import io.renren.modules.sys.form.SysLoginForm;
import io.renren.modules.sys.service.CaptchaService;
import io.renren.modules.sys.service.UserService;
import io.renren.modules.sys.service.UserTokenService;

/**
 * 登录相关
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@RestController
public class LoginController extends AbstractController {
	@Autowired
	private UserService userService;
	@Autowired
	private UserTokenService userTokenService;
	@Autowired
	private CaptchaService captchaService;

	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = captchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public RV login(@RequestBody SysLoginForm form)throws IOException {
		boolean captcha = captchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			throw new BizException("CODE_SYS_01", "验证码不正确");
		}

		//用户信息
		User user = userService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			
			throw new BizException("CODE_SYS_02", "账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			throw new BizException("CODE_SYS_03", "账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		return RV.ok(userTokenService.createToken(user.getUserId()));
	}


	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public RV logout() {
		userTokenService.logout(getUserId());
		return RV.ok();
	}
	
}
